package com.info.zhiduoduo.admin.service;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.info.zhiduoduo.admin.model.formbean.foreign.*;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.RandomUtil;
import com.info.zhiduoduo.common.utils.StringUtil;
import com.info.zhiduoduo.core.service.common.BaseService;
import com.info.zhiduoduo.repository.dto.foreign.ForeignProjectInvoiceListDto;
import com.info.zhiduoduo.repository.dto.foreign.MergeInvoiceListDto;
import com.info.zhiduoduo.repository.entity.foreign.ForeignInvoice;
import com.info.zhiduoduo.repository.mapper.foreign.ForeignInvoiceMapper;
import com.info.zhiduoduo.wxsdk.utils.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @program: zhiduoduo
 * @author: LiTong
 * @create: 2020-11-11 19:30
 **/
@Slf4j
@Service
public class ForeignProjectInvoiceService extends BaseService {

    @Resource
    ForeignInvoiceMapper foreignInvoiceMapper;

    /**
     * 第三方项目发票列表
     * @param formBean
     * @return
     */
    public SmartResult<ForeignProjectInvoiceListDto> foreignInvoice(@RequestBody BaseSimpleFormBean<ForeignProjectInvoiceFrombean> formBean) {
        ForeignProjectInvoiceFrombean reqdata = formBean.getReqdata();
        int state = reqdata.getState();
        String name = reqdata.getName();
        Date startDate = reqdata.getStartDate();
        Date endDate = reqdata.getEndDate();
        String sort = reqdata.getSort();
        int moneyCondition = reqdata.getMoneyCondition();
        String startAmount = reqdata.getStartAmount();
        String endAmount = reqdata.getEndAmount();
        if (startDate == null) {
            startDate = new Date(0);
        }
        if (endDate == null) {
            endDate = new Date();
        }
        String str;
        if (!StringUtil.isEmpty(sort)) {
            str = " ORDER BY invoice.amount " + sort;
        } else {
            str = " ORDER BY invoice.createtime";
        }
        Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
        List<ForeignProjectInvoiceListDto> list = foreignInvoiceMapper.foreignInvoice(name,startDate,endDate,state,str,moneyCondition,startAmount,endAmount);
        return smartResult(list,page.getTotal(), page.getPages(), page.getPageNum());
    }

    /**
     * 申请开票
     * @param formBean
     * @return
     */
    public SmartResult applyForInvoice(@RequestBody BaseSimpleFormBean<ApplyForForeignInvoiceFromBean> formBean) {
        if (null == formBean || 0 == formBean.getReqdata().getId() || 0 == formBean.getReqdata().getInvoiceCityId()) {
            return errorParamSmartResult();
        }
        ApplyForForeignInvoiceFromBean invoiceFromBean = formBean.getReqdata();
        if (StringUtil.isAnyEmpty(invoiceFromBean.getEntrustedOperator(), invoiceFromBean.getProjectServiceName())) {
            return errorParamSmartResult();
        }
        ForeignInvoice foreignInvoice = new ForeignInvoice().selectById(invoiceFromBean.getId());
        if (null == foreignInvoice) {
            return smartResult(StatusMsg.StatusMsg_930);
        }
        //客服输入的 委托运营方 和 项目服务名称 更新到 该条发票记录，并更新状态为 开票中
        foreignInvoice.setEntrustedOperator(invoiceFromBean.getEntrustedOperator())
                .setProjectServiceName(invoiceFromBean.getProjectServiceName())
                .setInvoiceCityId(invoiceFromBean.getInvoiceCityId()).setState(Constants.FOREIGN_INVOICE_STATE_2);
        if (!foreignInvoice.updateById()) {
            return smartResult(StatusMsg.StatusMsg_199);
        }
        return smartResult();
    }

    /**
     * 完成开票
     * @param formBean
     * @return
     */
    @Transactional
    public SmartResult completeInvoice(@RequestBody BaseSimpleFormBean<CompleteForeignInvoiceFromBean> formBean) {
        if (null == formBean || 0 == formBean.getReqdata().getId()) {
            return errorParamSmartResult();
        }
        CompleteForeignInvoiceFromBean invoiceFromBean = formBean.getReqdata();
        if (StringUtil.isAnyEmpty(invoiceFromBean.getCourierNumber(), invoiceFromBean.getCourierServicesCompany())) {
            return errorParamSmartResult();
        }
        ForeignInvoice foreignInvoice = new ForeignInvoice().selectById(invoiceFromBean.getId());
        if (null == foreignInvoice) {
            return smartResult(StatusMsg.StatusMsg_930);
        }
        //客服输入的 快递公司 和 快递单号 备注 更新到 该条发票记录，并更新状态为 已开票
        foreignInvoice.setCourierServicesCompany(invoiceFromBean.getCourierServicesCompany())
                .setCourierNumber(invoiceFromBean.getCourierNumber())
                .setRemarks(invoiceFromBean.getRemarks())
                .setState(Constants.FOREIGN_INVOICE_STATE_3)
                .setInvoicePicturePath(invoiceFromBean.getInvoicePicturePath());

        if (1 == foreignInvoice.getWhetherMerge()) {
            //为合并后的发票   需要把单条发票也给更新状态
            List<ForeignProjectInvoiceListDto> list = foreignInvoiceMapper.queryAllRelationInvoice(foreignInvoice.getId());
            list.forEach(invoiceList->{
                ForeignInvoice singleInvoice = new ForeignInvoice().selectById(invoiceList.getId());
                singleInvoice.setCourierServicesCompany(invoiceFromBean.getCourierServicesCompany())
                        .setCourierNumber(invoiceFromBean.getCourierNumber()).setRemarks(foreignInvoice.getRemarks())
                        .setState(Constants.FOREIGN_INVOICE_STATE_3).updateById();
            });
        }
        if (!foreignInvoice.updateById()) {
            return smartResult(StatusMsg.StatusMsg_199);
        }
        return smartResult();
    }

    /**
     * 多条合并申请开票
     * @param formBean
     * @return
     */
    @Transactional
    public SmartResult mergeApplyForInvoice(@RequestBody BaseSimpleFormBean<MergeApplyForInvoiceFormBean> formBean) {
        if (null == formBean || null == formBean.getReqdata().getIds() || 2 > formBean.getReqdata().getIds().size()
                || 0 == formBean.getReqdata().getInvoiceCityId() || 0 == formBean.getReqdata().getType()) {
            return errorParamSmartResult();
        }
        MergeApplyForInvoiceFormBean invoiceFormBean = formBean.getReqdata();
        if (StringUtil.isAnyEmpty(invoiceFormBean.getEntrustedOperator(),invoiceFormBean.getProjectServiceName())) {
            return errorParamSmartResult();
        }
        List<Integer> ids = invoiceFormBean.getIds();
        BigDecimal amount = new BigDecimal("0");
        ForeignInvoice bigInvoice = new ForeignInvoice();
        //新增一个合并后的发票数据 状态直接为开票中
        bigInvoice.setAmount(amount).setState(2).setWhetherMerge(1).insert();
        for (Integer id : ids) {
            ForeignInvoice foreignInvoice = new ForeignInvoice().selectById(id);
            if (null == foreignInvoice) {
                LogUtil.error("id为" + id + "的该第三方项目发票信息不存在");
                return smartResult(StatusMsg.StatusMsg_930);
            }
            //多条开票记录中的开票金额相加
            amount = amount.add(foreignInvoice.getAmount());
            //被合并的发票数据关联到 新生成的数据上  并且也 更新到开票中的状态
            foreignInvoice.setMergeId(bigInvoice.getId()).setState(2)
                    .setEntrustedOperator(invoiceFormBean.getEntrustedOperator())
                    .setProjectServiceName(invoiceFormBean.getProjectServiceName())
                    .setInvoiceCityId(invoiceFormBean.getInvoiceCityId()).updateById();
        }
        bigInvoice.setAmount(amount)
                .setEntrustedOperator(invoiceFormBean.getEntrustedOperator())
                .setProjectServiceName(invoiceFormBean.getProjectServiceName())
                .setType(invoiceFormBean.getType())
                .setMergeRemarks(invoiceFormBean.getMergeRemarks())
                .updateById();
        return smartResult();
    }

    /**
     * 第三方项目发票列表-合并开票列表
     * @param formBean
     * @return
     */
    public SmartResult<MergeInvoiceListDto> mergeInvoiceList(@RequestBody BaseSimpleFormBean<MergeInvoiceFrombean> formBean) {
        MergeInvoiceFrombean reqdata = formBean.getReqdata();
        int state = reqdata.getState();
        String name = reqdata.getName();
        Date startDate = reqdata.getStartDate();
        Date endDate = reqdata.getEndDate();
        if (startDate == null) {
            startDate = new Date(0);
        }
        if (endDate == null) {
            endDate = new Date();
        }
        Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
        List<MergeInvoiceListDto> list = foreignInvoiceMapper.mergeInvoiceList(name,startDate,endDate,state);
        return smartResult(list,page.getTotal(), page.getPages(), page.getPageNum());
    }


    /**
     * 查看关联的所有单条发票信息
     * @param formBean
     * @return
     */
    public SmartResult queryAllRelationInvoice(@RequestBody BaseSimpleFormBean<Integer> formBean) {
        if (null == formBean.getReqdata()) {
            return errorParamSmartResult();
        }
        List<ForeignProjectInvoiceListDto> list = foreignInvoiceMapper.queryAllRelationInvoice(formBean.getReqdata());
        return smartResult(list);
    }

    /**
     * 导出合并开票的明细
     * @param response response
     * @param invoiceId 发票id
     */
    public void exportMergeInvoiceInfo(HttpServletResponse response, int invoiceId) {

        List<ForeignProjectInvoiceListDto> list = foreignInvoiceMapper.queryAllRelationInvoice(invoiceId);

        String file = RandomUtil.createRandomNo( "合并开票明细", "");
        try {
            EasyExcel.write(getExcelOutPutStream(response, file), ForeignProjectInvoiceListDto.class).sheet("合并开票明细").doWrite(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
